package edu.nf.llmtest.service.Handler;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import edu.nf.llmtest.common.annotation.MessageType;
import edu.nf.llmtest.mapper.EssayMapper;
import edu.nf.llmtest.mapper.SessionMapper;
import edu.nf.llmtest.model.dto.EssayDTO;
import edu.nf.llmtest.model.dto.MessageEnvelope;
import edu.nf.llmtest.model.entity.Essay;
import edu.nf.llmtest.model.entity.Session;
import edu.nf.llmtest.service.EssayService;
import edu.nf.llmtest.service.impl.JinaEmbeddingService;
import edu.nf.llmtest.service.impl.QdrantVectorService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @ Author bin
 * @ Create  2025/11/24 10:34
 * 添加文章
 **/
@MessageType("addEssayHanlder")
@Service
@Slf4j
@RequiredArgsConstructor
public class AddEssayHanlder implements MessageHandler{
    private final ObjectMapper objectMapper = new ObjectMapper();
    private final EssayMapper essayMapper;
    private final EssayService essayService;
    private final QdrantVectorService qdrantVectorService;
    private final JinaEmbeddingService jinaEmbeddingService;

    @Override
    public void handle(Message message) {
        String body = new String(message.getBody(), StandardCharsets.UTF_8);

        try {
            MessageEnvelope<Essay> wrapper = objectMapper.readValue(
                    body,
                    new TypeReference<MessageEnvelope<Essay>>() {}
            );
            Essay essay = wrapper.getData();
            //插入文章
            Integer eId = essayMapper.addEssay(essay);
            //同步文章到Redis和Elasticsearch中
//            EssayDTO essayDTO = essayService.getEssayById(eId);
//            List<Float> block = jinaEmbeddingService.embedText(essayDTO.getTitle()).block();
//            qdrantVectorService.upsertPoint(eId,block,essayDTO.toString());
        } catch (Exception e) {
            log.error("解析用户消息失败: {}", body, e);
        }
    }
}
